package com.fili;

import gnu.io.*;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.Enumeration;
import java.util.TooManyListenersException;

/**
 * Created by IntelliJ IDEA.
 * User: fili
 * Date: Sep 23, 2006
 * Time: 9:05:55 PM
 * To change this template use File | Settings | File Templates.
 */
public class STest
{
    public static void main(String[] args)
    {
        Enumeration portId = CommPortIdentifier.getPortIdentifiers();
        CommPortIdentifier spid = null;

        while (portId.hasMoreElements())
        {
            CommPortIdentifier pid = (CommPortIdentifier) portId.nextElement();
            if (pid.getPortType() == CommPortIdentifier.PORT_SERIAL)
            {
                System.out.println("found: " + pid.getName() + " " + pid.getPortType());
                spid = pid;
            }
        }

        if (spid == null)
        {
            System.out.println("No serial ports found");
            System.exit(1);
        }

        SerialPort sPort = null;

        try
        {
            sPort = (SerialPort) spid.open("My App", 10000);
        }
        catch (PortInUseException e)
        {
            e.printStackTrace();
            System.exit(1);
        }

        try
        {
            sPort.addEventListener(new SerialPortEventListener()
            {
                public void serialEvent(SerialPortEvent serialPortEvent)
                {
                }
            });
        }
        catch (TooManyListenersException e)
        {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        try
        {
            sPort.setSerialPortParams(115200, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
        }
        catch (UnsupportedCommOperationException e)
        {
            e.printStackTrace();
            System.exit(1);
        }

        BufferedReader is = null;
        PrintStream os = null;

        try
        {
            is = new BufferedReader(new InputStreamReader(sPort.getInputStream()));
            os = new PrintStream(sPort.getOutputStream(), true);
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }

        System.out.println("ALL OK");


        try
        {
            if (is != null)
            {
                is.close();
                is = null;
            }
            if (os != null)
            {
                os.close();
                os = null;
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }

        sPort.close();

    }
}
